import { type LoginUser } from '@/server'
import { tokenName } from '@/server/base'

let state: {
  username: string
  total: number
  accessToken: string
  user: string
  userInfo: LoginUser | null
} = {
  username: '',
  total: 0,
  accessToken: '',
  user: '',
  userInfo: getUserInfo()
}

function getUserInfo(): LoginUser | null {
  const userStr = localStorage.getItem(tokenName)
  if (!userStr) {
    return null
  }
  try {
    const userInfo = JSON.parse(userStr) as LoginUser
    return userInfo
  } catch (error) {
    return null
  }
}

let getters = {
  accessToken: (state: any) => getUserInfo()?.token,
  username: (state: any) => getUserInfo()?.name,
  account: (state: any) => getUserInfo()?.account,
  carId: (state: any) => getUserInfo()?.carid,
  userInfo: (state: any): LoginUser | null => {
    state.userInfo = getUserInfo()
    return state.userInfo
  }
}
let mutations = {
  /**
   * 设置用户信息
   */
  setUserInfo(state: any, userInfo: LoginUser) {
    //carid 作为token
    userInfo.token = userInfo.token || userInfo.carid + ''
    const userString = JSON.stringify(userInfo)
    localStorage.setItem(tokenName, userString)
    state.userInfo = userInfo
    //设置用户名
    state.username = userInfo.name
    state.user = userInfo.account
    //设置token carid 作为token
    state.accessToken = userInfo.token
  },
  /**
   * 退出
   */
  loginOut(state: any, isReload: boolean) {
    localStorage.removeItem(tokenName)
    state.userInfo = null
    try {
      if (isReload) {
        setTimeout(() => {
          window.location.reload()
        }, 500)
      }
    } catch (error) {}
  }
}
let actions = {
  //   testActions({ commit }: any, num: number) {
  // setTimeout(() => {
  //     commit('setTotal', num)
  //     console.log(num)
  // }, 2000)
  //   }
}
export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
